import {
  Inject,
  Controller,
  Get,
  Post,
  Files,
  Query,
  Body,
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { PREFIX } from '../contanst';
import { BaseController } from './base.controller';
import { FileService } from '../service/file.service';
import { EXCEL_MAP } from '../contanst/erpOrders';
import { ErpOrdersService } from '../service/erpOrders.service';
import { toLower } from 'lodash';
import { Like } from 'typeorm';

const DESCRIPTION = 'ERP订单';

@Controller(PREFIX)
export class APIController extends BaseController {
  @Inject()
  ctx: Context;

  @Inject()
  erpOrdersService: ErpOrdersService;

  @Get('/erpOrders', {
    description: `${DESCRIPTION}列表`,
  })
  async index(
    @Query('size') size = 10,
    @Query('page') page = 1,
    @Query('erp_data_date') erp_data_date,
    @Query('store_name') store_name,
    @Query('order_number') order_number,
    @Query('erp_order_number') erp_order_number
  ) {
    const erpOrders = await this.erpOrdersService.page({
      data: {
        size,
        page,
        erp_data_date,
        store_name: store_name && Like(`%${store_name}%`),
        order_number: order_number && Like(`%${order_number}%`),
        erp_order_number: order_number && Like(`%${erp_order_number}%`),
      },
    });
    return this.success(erpOrders);
  }

  @Inject()
  file: FileService;

  @Post('/erpOrders/import', {
    description: `${DESCRIPTION}导入`,
  })
  async import(@Files() files, @Body('erp_data_date') erp_data_date) {
    const file = files[0];
    const data: any = await this.file.importExcel(file);
    const tableData = data?.[0]?.data;
    const tableHeader = tableData?.[0];
    const tableBody = tableData?.splice?.(1);
    const obj = {};

    Object.keys(EXCEL_MAP).forEach(key => {
      const index = tableHeader?.findIndex?.(item => {
        return toLower(item).trim() === toLower(key).trim();
      });
      if (index > -1) {
        obj[EXCEL_MAP[key]] = index;
      }
    });

    const records: any[] = [];

    tableBody.forEach(item => {
      if (
        item[obj['order_source']] === "'手工建单" ||
        item[obj['order_source']] === '手工建单'
      ) {
        return;
      }
      const record: any = {};
      Object.keys(obj).map(key => {
        record[key] = item[obj[key]]?.replace?.(/\t/g, '') || item[obj[key]];
      });
      record.erp_data_date = erp_data_date;
      if (typeof record.cost === 'number') {
        records.push(record);
      }
    });

    this.erpOrdersService.upsert(records);

    return this.success();
  }
}
